<template>
  <div>
    <dialog-edit :visible.sync="dialogVisible" :title="$attrs.title" ref="userManageEdit" width="90%" height="90%"
                 @save="save" :remember="false" :destroyOnClose="true" @zoom="zoom"
                 :saveFlag="true" :loading="loading" :escClosable="true" :closeFlag="true" :saveLoading="saveLoading">
      <template v-slot:body>
        <div ref="dialog" :style="{
           'flex-direction': 'column',
            'height': dialogHeight
          }">
          <search-component :colum="colum" :formValue="formValue" class="search"
                            @search="search" @reset="reset" ref="search">
          </search-component>
          <vxe-grid
              style="flex: 1"
              border
              context-menu
              highlight-hover-row
              :scroll-y="{gt: -1}"
              resizable
              :data="tableData"
              :height="tableHeight"
              :loading="loading"
              ref="gridTable"
              :pager-config="pagerConfig"
              :radio-config="{labelField: 'name', highlight: true, trigger: 'row', range: true}"
              @page-change="pageChangeChange">
            <vxe-table-column type="radio" width="40"></vxe-table-column>
            <vxe-table-column field="Id" title="编号" :width="'160px'" sortable></vxe-table-column>
            <vxe-table-column field="Modulename" title="模块" :width="'120px'" sortable></vxe-table-column>
            <vxe-table-column field="Level" title="级别" align="center" :width="'72px'" sortable>
              <template v-slot="{ row }">
                <el-tag :type="tagType[row.Level-1]">
                  {{ statusFilterOptions(row.Level, 'LEVEL') }}
                </el-tag>
              </template>
            </vxe-table-column>
            <vxe-table-column field="Name" title="反馈标题" :min-width="'250px'" sortable>
              <template v-slot="{ row }">
                <span>{{row.Name}}</span>
              </template>
            </vxe-table-column>
            <vxe-table-column field="Type" title="分类" align="center" :width="'85px'" sortable>
              <template v-slot="{ row }">
                <span>{{ statusFilterOptions(row.Type, 'TEST_TYPE') }}</span>
              </template>
            </vxe-table-column>
            <vxe-table-column field="Status" title="状态" align="center" :width="'110px'" sortable>
              <template v-slot="{ row }">
                <span>{{ statusFilterOptions(row.Status, 'TEST_STATUS') }}</span>
              </template>
            </vxe-table-column>
            <vxe-table-column field="Userrealname" title="创建人" width="100" sortable></vxe-table-column>
            <vxe-table-column field="Departname" title="部门" width="120" sortable></vxe-table-column>
            <vxe-table-column field="Created" title="创建日期" :formatter="formatDate" width="100" sortable ></vxe-table-column>
            <vxe-table-column field="Acceptrealname" title="指派人" width="90" sortable></vxe-table-column>
            <vxe-table-column field="Completerealname" title="解决人" width="90" sortable></vxe-table-column>
            <vxe-table-column field="Completed" title="解决日期" :formatter="formatDate" width="100" sortable></vxe-table-column>
            <vxe-table-column field="Changed" title="最后更新日期" :formatter="formatDate" width="150" sortable ></vxe-table-column>
          </vxe-grid>
        </div>
      </template>
    </dialog-edit>
  </div>
</template>

<script>
import dialogEdit from '@/components/element/dialogEdit'
import searchComponent from "@/components/element/layoutComponents/searchFrom/searchComponent.vue";
import DictionarySelect from "@/components/element/select/DictionarySelect";
import SelectProjectModule from "@/components/element/select/SelectProjectModule";
import SelectProjectTeam from "@/components/element/select/SelectProjectTeam";
import SelectDepart from "@/components/element/select/SelectDepart";
import projectTestApi from "@/api/projectTestApi";
import {mapGetters} from "vuex";
import { formatDateString } from '@/utils/date'
export default {
  name: 'testDialog',
  components: {
    searchComponent,
    dialogEdit,
    SelectProjectTeam
  },
  props: {
    visible: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    preFormData: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  computed: {
    ...mapGetters(['dictionary']),
    statusList() {
      return (DictTypeCode) => {
        return this.dictionary.filter(item => item.DictTypeCode === DictTypeCode)
      }
    },
    linkName () {
      return (row) => {
        let hp = window.location.protocol
        let host = window.location.host
        return `${hp}//${host}/view/test/show/${row.Id}`
      }
    },
    statusFilterOptions() {
      return (cellValue, DictTypeCode) => {
        let filter = this.statusList(DictTypeCode).filter(it => it.DictId === cellValue.toString())
        if (filter.length > 0) {
          return filter[0].DictName
        }
        return ''
      }
    },
    dialogVisible: {
      get () {
        return this.visible
      },
      set (value) {
        this.$emit('update:visible', value)
      }
    }
  },
  data() {
    return {
      tableHeight: '400px',
      dialogHeight: 'calc(100% - 40px)',
      saveLoading: false,
      loading: false,
      tagType: ['danger', 'warning', 'info', 'success'],
      fullscreenLoading: false,
      formValue: {
        p: 1,
        pageoffset: 15
      },
      colum: [
        {
          placeholder: '请选择状态',
          prop: 'status',
          size: 'small',
          dictTypeCode: 'TEST_STATUS',
          componentName: DictionarySelect,
          value: 'status',
          clearable: true,
          show: true,
          multiple: true,
          elcolStyle: {
            'width': '200px'
          }
        },
        {
          placeholder: '请选择分类',
          prop: 'type',
          size: 'small',
          dictTypeCode: 'TEST_TYPE',
          componentName: DictionarySelect,
          value: 'type',
          clearable: true,
          show: true,
          multiple: true,
          elcolStyle: {
            'width': '200px'
          }
        },
        // {
        //   placeholder: '请选择级别',
        //   prop: 'level',
        //   size: 'small',
        //   dictTypeCode: 'LEVEL',
        //   componentName: DictionarySelect,
        //   value: 'level',
        //   clearable: true,
        //   show: true,
        //   multiple: true,
        //   elcolStyle: {
        //     'width': '200px'
        //   }
        // },
        {
          placeholder: '请选择指派人',
          selectTitle: '指派人',
          prop: 'acceptid',
          size: 'small',
          componentName: SelectProjectTeam,
          value: 'acceptid',
          ref: 'acceptid',
          clearable: true,
          show: true,
          attrs: {
            multiple: true,
            column: [
              { field: 'Userrealname' }
            ],
            showValueShow: []
          },
          elcolStyle: {
            'width': '200px'
          }
        },
        {
          placeholder: '请选择模块',
          prop: 'moduleid',
          size: 'small',
          componentName: SelectProjectModule,
          data: 'URL',
          value: 'moduleid',
          ref: 'moduleid',
          clearable: true,
          show: true,
          attrs: {
            multiple: true,
            column: [
              { field: 'Name', title: '模块名称' }
            ],
          },
          elcolStyle: {
            'width': '200px'
          }
        },
        {
          placeholder: '请选择反馈环境',
          prop: 'env',
          size: 'small',
          dictTypeCode: 'ENV',
          componentName: DictionarySelect,
          value: 'env',
          clearable: true,
          show: true,
          multiple: true,
          elcolStyle: {
            'width': '200px'
          }
        },
        {
          placeholder: '请选择创建人',
          selectTitle: '创建人',
          prop: 'creatId',
          size: 'small',
          componentName: SelectProjectTeam,
          value: 'creatId',
          ref: 'creatId',
          clearable: true,
          show: true,
          attrs: {
            multiple: true,
            showValueShow: [],
            column: [
              { field: 'Userrealname' }
            ]
          },
          elcolStyle: {
            'width': '200px'
          }
        },
        {
          placeholder: '创建人部门',
          selectTitle: '创建人部门',
          prop: 'departid',
          size: 'small',
          componentName: SelectDepart,
          value: 'departid',
          ref: 'departid',
          clearable: true,
          show: true,
          attrs: {
            multiple: true
          },
          elcolStyle: {
            'width': '200px'
          }
        },
        {
          placeholder: '请选择创建开始时间',
          prop: 'createStarted',
          size: 'small',
          componentName: 'el-date-picker',
          value: 'createStarted',
          clearable: true,
          show: true,
          multiple: true,
          attrs: {
            'value-format': 'timestamp'
          },
          elcolStyle: {
            'width': '200px'
          }
        },
        {
          placeholder: '请选择创建结束时间',
          prop: 'createEnd',
          size: 'small',
          componentName: 'el-date-picker',
          value: 'createEnd',
          clearable: true,
          show: true,
          multiple: true,
          attrs: {
            'value-format': 'timestamp'
          },
          elcolStyle: {
            'width': '200px'
          }
        },
        {
          placeholder: '请输入反馈标题',
          prop: 'keywords',
          size: 'small',
          componentName: 'vxe-input',
          type: 'integer',
          min: 0,
          value: 'keywords',
          clearable: true,
          show: true,
          elcolStyle: {
            'width': '200px'
          }
        },
        {
          placeholder: '请输入反馈编号',
          prop: 'testno',
          size: 'small',
          componentName: 'vxe-input',
          value: 'testno',
          clearable: true,
          show: true,
          elcolStyle: {
            'width': '200px'
          }
        }
      ],
      tableData: [],
      // toolbar: {
      //   slots: {
      //     buttons: 'toolbar-buttons'
      //   },
      // },
      pagerConfig: {
        currentPage: 1,
        pageSize: 15,
        total: 0,
        pagerCount: 7,
        pageSizes: [10, 15, 20, 50, 100]
      }
    }
  },
  methods: {
    getPositionTop (node) { // 获取元素到顶部距离-通用方法
      if (node === null) {
        return 0
      }
      var top = node.offsetTop
      var parent = node.offsetParent
      while (parent != null) {
        top += parent.offsetTop
        parent = parent.offsetParent
      }
      return top // 所有的父元素top和
    },
    search(a) {
      this.tableData = []
      let query1 = Object.assign({}, this.formValue)
      let query = JSON.parse(JSON.stringify(query1))
      if (query.createStarted) {
        query.createStarted = query.createStarted / 1000
      }
      if (query.createEnd) {
        query.createEnd = query.createEnd / 1000
      }
      if (query.createStarted && query.createEnd && query.createStarted === query.createEnd) {
        query.createEnd = query.createEnd + (60 * 60 * 24)
      }
      this.loading = true
      projectTestApi.getPage(query).then(res => {
        if (res && res.Tests) {
          this.tableData = res.Tests;
          this.pagerConfigFun(res)
          if (this.$router.currentRoute.params.pid && a === '1') {
            if (this.tableData.length > 0) {
              this.editDetil(this.tableData[0])
            }
          }
        } else if (null === res.Tests) {
          this.tableData = []
          this.pagerConfigFun(res)
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => this.$message.error('获取反馈信息失败')).finally(() => this.loading = false);
    },
    reset() {
      this.formValue = {
        p: 1,
        pageoffset: 15
      }
    },
    pagerConfigFun(res) {
      this.pagerConfig.currentPage = res.Page
      this.formValue.p = this.pagerConfig.currentPage
      this.pagerConfig.total = res.Total
    },
    pageChangeChange(pageConfig) {
      this.formValue.p = pageConfig.currentPage
      this.pagerConfig.currentPage = pageConfig.currentPage
      this.formValue.pageoffset = pageConfig.pageSize
      this.pagerConfig.pageSize = pageConfig.pageSize
      this.search()
    },
    formatDate ({ cellValue }) {
      let a = formatDateString(cellValue * 1000, 'yyyy-MM-dd hh:mm:ss')
      if (a.indexOf('1970-01-01') >= 0 ) {
        return ''
      }
      return a
    },
    initData () {
      let a = ''
      this.$set(this.formValue, 'id', this.preFormData.Projectid)
      this.search(a)
    },
    // 保存
    save () {
      this.saveLoading = true
      let a = this.$refs.gridTable.getRadioRecord()
      if (a) {
        this.$emit('selectData', a)
        this.dialogVisible = false
        this.saveLoading = false
      }
    },
    // init初始化
    initProject () {
      let that = this
      setTimeout(function () {
        that.colum.forEach(it => {
          if (it.prop === 'acceptid' || it.prop === 'creatId' || it.prop === 'departid' || it.prop === 'moduleid') {
            // this.$set(it, 'attrs', it.attrs || {})
            that.$set(it.attrs, 'queryValue', {
              id: that.preFormData.Projectid
            })
          }
        })
      }, 1500)
    },
    calcHeight () {
      this.$nextTick(() => {
        console.log(this.getPositionTop(this.$refs.gridTable.$el))
        let a = this.getPositionTop(this.$refs.gridTable.$el + 'px')

        this.dialogHeight = (`calc(100% - ${a})`)
        this.$nextTick(() => {
          // console.log(this.$refs.dialog.clientHeight)
          // console.log(this.$refs.search.$el.clientHeight)
          // this.tableHeight = this.$refs.dialog.clientHeight - this.$refs.search.$el.clientHeight
          this.tableHeight =this.$refs.dialog.clientHeight- this.$refs.search.$el.clientHeight
          // console.log(this.tableHeight )
          //暂时
          if(this.tableHeight<400){
            this.tableHeight=500
          }
          this.tableHeight = this.tableHeight + 'px'
        })
      })
    },
    zoom ({ type, $event }) {
      console.log(type, $event)
      this.calcHeight()
    }
  },
  watch: {
    dialogVisible: {
      immediate: true,
      deep: true,
      handler (n, o) {
        if (n) {
          this.initData()
          this.initProject()
          this.calcHeight()
        }
      }
    }
  }
}
</script>
<style>
.headButton {
  text-align: right;
  padding-bottom: 10px;
}

.headButton .title {
  float: left;
  font-width: normal;
  font-size: 20px;
}

.link-name {
  color: #65CEA7;
}

.link-name:hover {
  color: #353F4F;
  cursor: pointer;
}
</style>
